<?php

namespace common\business;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/28
 * Time: 12:33
 */
use common\business\mdm\MdmApiHandler;
use common\business\upload\UploadHelper;
use common\consts\CommonResources;
use common\consts\Consts;
use common\helpers\DbHelper;
use common\helpers\StringUtil;
use common\models\Department;
use common\models\EmployeePhoto;
use common\models\kingdee\CertifyCompetency;
use common\models\kingdee\CertifyCompetencyType;
use common\models\kingdee\CtrlUnit;
use common\models\kingdee\DimissionReason;
use common\models\kingdee\Domain;
use common\models\kingdee\EmployeeModle;
use common\models\kingdee\EnrollSource;
use common\models\kingdee\HrEmployeeFenlei;
use common\models\kingdee\HrEmployeeType;
use common\models\kingdee\HrFolk;
use common\models\kingdee\HrHealth;
use common\models\kingdee\HrPersonPhoto;
use common\models\kingdee\HrPolitical;
use common\models\kingdee\HrSSocArea;
use common\models\kingdee\HrSSocCensus;
use common\models\kingdee\HrWed;
use common\models\kingdee\Industry;
use common\models\kingdee\Nationality;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\OrgLayerType;
use common\models\kingdee\OrgPosition;
use common\models\kingdee\OrgProperty;
use common\models\kingdee\Person;
use common\models\kingdee\Regpermresidence;
use common\models\kingdee\UserGroup;
use common\models\mdm\MdmDept;
use common\models\mdm\MdmOrg;
use common\models\User;
use Yii;
use yii\db\Exception;
use yii\db\Query;
use yii\db\QueryInterface;
use yii\helpers\ArrayHelper;


class EhrHelper
{
    public static function getPersonNameById($id)
    {
        $obj = Person::findOne($id);
        if (!isset($obj) || $obj == null) {
            return Yii::t('app', 'No Record Found');
        }

        return $obj->FNAME_L2;
    }

    public static function getCertifyCompetencyTypeById($id)
    {
        $obj = CertifyCompetencyType::findOne($id);
        if (!isset($obj) || $obj == null) {
            return Yii::t('app', 'No Record Found');
        }

        return $obj->FNAME_L2;
    }

    public static function getCertifyCompetencyById($id)
    {
        $obj = CertifyCompetency::findOne($id);
        if (!isset($obj) || $obj == null) {
            return Yii::t('app', 'No Record Found');
        }

        return $obj->FNAME_L2;
    }

    //region 得到报名状态键值对
    public static function getCertifyCompetencyType_map()
    {
        $objList = CertifyCompetencyType::find()->all();
        $returnArr = array();
        foreach ($objList as $element) {
            $returnArr[$element->FID] = $element->FNAME_L2;
        }
        return $returnArr;
    }
    //endregion

    //region 性别int和string值互换查询
    public static function getGender_map()
    {
        return [
            Consts::GENDER_MALE => Yii::t('app', 'Male'),
            Consts::GENDER_FEMALE => Yii::t('app', 'Female'),
            Consts::GENDER_NOT_DEFINED => Yii::t('app', 'Not Defined'),
        ];
    }

    public static function getGender_reverse_map()
    {
        return [
            Yii::t('app', 'Male') => Consts::GENDER_MALE,
            Yii::t('app', 'Female') => Consts::GENDER_FEMALE,
            Yii::t('app', 'Not Defined') => Consts::GENDER_NOT_DEFINED,
        ];
    }

    public static function getGenderByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getGender_map()[$intValue];
    }

    public static function getGenderByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getGender_reverse_map()[$intValue];
    }
    //endregion

    //region 状态int和string值互换查询
    public static function getAccessTokenStatus_map()
    {
        return [
            Consts::ACCESS_TOKEN_STATUS_ACTIVE => Yii::t('app', 'Active'),
            Consts::ACCESS_TOKEN_STATUS_INACTIVE => Yii::t('app', 'In Active'),
        ];
    }

    public static function getAccessTokenStatus_reverse_map()
    {
        return [
            Yii::t('app', 'Active') => Consts::ACCESS_TOKEN_STATUS_ACTIVE,
            Yii::t('app', 'In Active') => Consts::ACCESS_TOKEN_STATUS_INACTIVE,
        ];
    }

    public static function getAccessTokenByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getAccessTokenStatus_map()[$intValue];
    }

    public static function getAccessTokenByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getAccessTokenStatus_reverse_map()[$intValue];
    }
    //endregion

    //region 微信用户状态int和string值互换查询
    public static function getQywxUserStatus_map()
    {
        return [
            Consts::QYWX_USER_STATUS_ACTIVATED => Yii::t('app', 'Activated'),
            Consts::QYWX_USER_STATUS_DISABLED => Yii::t('app', 'Disabled'),
            Consts::QYWX_USER_STATUS_UN_ACTIVATED => Yii::t('app', 'Un Activated'),
        ];
    }

    public static function getQywxUserStatus_reverse_map()
    {
        return [
            Yii::t('app', 'Activated') => Consts::QYWX_USER_STATUS_ACTIVATED,
            Yii::t('app', 'Disabled') => Consts::QYWX_USER_STATUS_DISABLED,
            Yii::t('app', 'Un Activated') => Consts::QYWX_USER_STATUS_UN_ACTIVATED,
        ];
    }

    public static function getQywxUserStatusByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getQywxUserStatus_map()[$intValue];
    }

    public static function getQywxUserStatusByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getQywxUserStatus_reverse_map()[$intValue];
    }
    //endregion

    //region 是和否的int和string值互换查询
    public static function getYesOrNo_map()
    {
        return [
            Consts::YES => Yii::t('app', 'Yes'),
            Consts::NO => Yii::t('app', 'No'),
        ];
    }

    public static function getYesOrNo_reverse_map()
    {
        return [
            Yii::t('app', 'Yes') => Consts::YES,
            Yii::t('app', 'No') => Consts::NO,
        ];
    }

    public static function getYesOrNoByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getYesOrNo_map()[$intValue];
    }

    public static function getYesOrNoByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getYesOrNo_reverse_map()[$intValue];
    }
    //endregion

    //region 是否为Leader int和string值互换查询
    public static function getQywxUserIsLeader_map()
    {
        return [
            Consts::QYWX_USER_IS_LEADER => Yii::t('app', 'Yes'),
            Consts::QYWX_USER_IS_NOT_LEADER => Yii::t('app', 'No'),
        ];
    }

    public static function getQywxUserIsLeader_reverse_map()
    {
        return [
            Yii::t('app', 'Yes') => Consts::QYWX_USER_IS_LEADER,
            Yii::t('app', 'No') => Consts::QYWX_USER_IS_NOT_LEADER,
        ];
    }

    public static function getQywxUserIsLeaderByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getQywxUserIsLeader_map()[$intValue];
    }

    public static function getQywxUserIsLeaderByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getQywxUserIsLeader_reverse_map()[$intValue];
    }
    //endregion

    //region 同步状态 int和string值互换查询
    public static function getSyncStatus_map()
    {
        return Consts::SYNC_STATUS_MAP();
    }

    public static function getSyncStatus_reverse_map()
    {
        return CommonHelper::getReverseMap(self::getSyncStatus_map());
    }

    public static function getSyncStatusByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getSyncStatus_map()[$intValue];
    }

    public static function getSyncStatusByStrValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getSyncStatus_reverse_map()[$intValue];
    }
    //endregion

    //region 血型int和string值互换查询
    public static function getBloodType_map()
    {
        return [
            Consts::KD_BLOOD_TYPE_UN_KNOWN => Yii::t('app', 'Unknown'),
            Consts::KD_BLOOD_TYPE_A => 'A',
            Consts::KD_BLOOD_TYPE_B => 'B',
            Consts::KD_BLOOD_TYPE_AB => 'AB',
            Consts::KD_BLOOD_TYPE_O => 'O',
            Consts::KD_BLOOD_TYPE_OTHER => Yii::t('app', 'Other'),
        ];
    }

    public static function getBloodType_reverse_map()
    {
        return [
            Yii::t('app', 'Unknown') => Consts::KD_BLOOD_TYPE_UN_KNOWN,
            'A' => Consts::KD_BLOOD_TYPE_A,
            'B' => Consts::KD_BLOOD_TYPE_B,
            'AB' => Consts::KD_BLOOD_TYPE_AB,
            'O' => Consts::KD_BLOOD_TYPE_O,
            Yii::t('app', 'Other') => Consts::KD_BLOOD_TYPE_OTHER,
        ];
    }

    public static function getBloodTypeByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getBloodType_map()[$intValue];
    }

    public static function getBloodTypeByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getBloodType_reverse_map()[$strValue];
    }
    //endregion

    //region 组织类型int和string值互换查询
    public static function getOrgType_map()
    {
        return [
            Consts::KD_ORG_TYPE_ADMIN => Yii::t('app', 'Admin'),
            Consts::KD_ORG_TYPE_FINANCE => Yii::t('app', 'Finance'),
            Consts::KD_ORG_TYPE_SALES => Yii::t('app', 'Sales'),
            Consts::KD_ORG_TYPE_PURCHASE => Yii::t('app', 'Purchase'),
            Consts::KD_ORG_TYPE_INVENTORY => Yii::t('app', 'Inventory'),
            Consts::KD_ORG_TYPE_COST_CENTER => Yii::t('app', 'Cost Center'),
            Consts::KD_ORG_TYPE_PROFIT_CENTER => Yii::t('app', 'Profit Center'),
            Consts::KD_ORG_TYPE_MERGE_RANGE => Yii::t('app', 'Merge Range'),
            Consts::KD_ORG_TYPE_CONTROL_UNIT => Yii::t('app', 'Control Unit'),
            Consts::KD_ORG_TYPE_HR => Yii::t('app', 'HR'),
            Consts::KD_ORG_TYPE_FORWARDING => Yii::t('app', 'Forwarding'),
            Consts::KD_ORG_TYPE_QUALITY_TEST => Yii::t('app', 'Quality Test'),
        ];
    }

    public static function getOrgType_reverse_map()
    {
        return [
            Yii::t('app', 'Admin') => Consts::KD_ORG_TYPE_ADMIN,
            Yii::t('app', 'Finance') => Consts::KD_ORG_TYPE_FINANCE,
            Yii::t('app', 'Sales') => Consts::KD_ORG_TYPE_SALES,
            Yii::t('app', 'Purchase') => Consts::KD_ORG_TYPE_PURCHASE,
            Yii::t('app', 'Inventory') => Consts::KD_ORG_TYPE_INVENTORY,
            Yii::t('app', 'Cost Center') => Consts::KD_ORG_TYPE_COST_CENTER,
            Yii::t('app', 'Profit Center') => Consts::KD_ORG_TYPE_PROFIT_CENTER,
            Yii::t('app', 'Merge Range') => Consts::KD_ORG_TYPE_MERGE_RANGE,
            Yii::t('app', 'Control Unit') => Consts::KD_ORG_TYPE_CONTROL_UNIT,
            Yii::t('app', 'HR') => Consts::KD_ORG_TYPE_HR,
            Yii::t('app', 'Forwarding') => Consts::KD_ORG_TYPE_FORWARDING,
            Yii::t('app', 'Quality Test') => Consts::KD_ORG_TYPE_QUALITY_TEST,
        ];
    }

    public static function getOrgTypeByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getOrgType_map()[$intValue];
    }

    public static function getOrgTypeByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getOrgType_reverse_map()[$strValue];
    }
    //endregion

    //region locale int和string值互换查询
    public static function getLocale_map()
    {
        return [
            Consts::KD_LOCALE_ENGLISH => Yii::t('app', 'English'),
            Consts::KD_LOCALE_SIMPLIFIED_CHINESE => Yii::t('app', 'Simplified Chinese'),
            Consts::KD_LOCALE_TRADITIONAL_CHINESE => Yii::t('app', 'Traditional Chinese'),
        ];
    }

    public static function getLocale_reverse_map()
    {
        return CommonHelper::getReverseMap(self::getLocale_map());
    }

    public static function getLocaleByEnumValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getLocale_map()[$intValue];
    }

    public static function getLocaleByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getLocale_reverse_map()[$strValue];
    }
    //endregion

    //region in service int和string值互换查询
    public static function getInService_map()
    {
        return Consts::KD_IN_SERVICE_MAP();
    }

    public static function getInService_reverse_map()
    {
        return CommonHelper::getReverseMap(self::getInService_map());
    }

    public static function getInServiceByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getInService_map()[$intValue];
    }

    public static function getInServiceByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getInService_reverse_map()[$strValue];
    }
    //endregion

    //region work relation int和string值互换查询
    public static function getWorkRelation_map()
    {
        return Consts::KD_WORK_RELATION_MAP();
    }

    public static function getWorkRelation_reverse_map()
    {
        return CommonHelper::getReverseMap(self::getWorkRelation_map());
    }

    public static function getWorkRelationByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getWorkRelation_map()[$intValue];
    }

    public static function getWorkRelationByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getWorkRelation_reverse_map()[$strValue];
    }
    //endregion

    //region user state int和string值互换查询
    public static function getUserState_map()
    {
        return Consts::KD_USER_STATE_MAP();
    }

    public static function getUserState_reverse_map()
    {
        return CommonHelper::getReverseMap(self::getUserState_map());
    }

    public static function getUserStateByIntValue($intValue)
    {
        if (!isset($intValue)) {
            return null;
        }
        return self::getUserState_map()[$intValue];
    }

    public static function getUserStateByStrValue($strValue)
    {
        if (!isset($strValue)) {
            return null;
        }
        return self::getUserState_reverse_map()[$strValue];
    }
    //endregion

    //region task type
    public static function getTaskTypeStr($val)
    {
        if (!isset($val)) {
            return null;
        }
        return Consts::TASK_TYPE_MAP()[$val];
    }
    //endregion

    //region task status
    public static function getTaskStatusStr($val)
    {
        if (!isset($val)) {
            return null;
        }
        return Consts::TASK_STATUS_MAP()[$val];
    }
    //endregion

    //region mdm_task flag
    public static function getMdmTaskFlagStr($val)
    {
        if (!isset($val)) {
            return null;
        }
        return Consts::MDM_TASK_FLAG_MAP()[$val];
    }
    //endregion

    //region 得到部门键值对
    public static function getDepartment_map()
    {
        $all = Department::find()
//            ->where([
//                'department_parent_qywx_id' => 190,
//            ])
            ->orderBy([
                'department_qywx_id' => SORT_ASC,
            ])->all();
        return ArrayHelper::map($all, 'department_qywx_id', 'department_name');
    }
    //endregion

    //region 获得 婚姻状况 值
    public static function getWedStrById($id)
    {
        $wedInDb = HrWed::findOne([
            'FID' => $id,
        ]);

        if (!isset($wedInDb) || empty($wedInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $wedInDb->FNAME_L2;
    }
    //endregion

    //region 获得 健康状况 值
    public static function getHealthStrById($id)
    {
        $healthInDb = HrHealth::findOne([
            'FID' => $id,
        ]);

        if (!isset($healthInDb) || empty($healthInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $healthInDb->FNAME_L2;
    }
    //endregion

    //region 获得 民族 值
    public static function getFolkStrById($id)
    {
        $folkInDb = HrFolk::findOne([
            'FID' => $id,
        ]);

        if (!isset($folkInDb) || empty($folkInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $folkInDb->FNAME_L2;
    }
    //endregion

    //region 获得 国籍状况 值
    public static function getNationalityStrById($id)
    {
        $nationalityInDb = Nationality::findOne([
            'FID' => $id,
        ]);

        if (!isset($nationalityInDb) || empty($nationalityInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $nationalityInDb->FNAME_L2;
    }
    //endregion

    //region 获得 户口类型 值
    public static function getRegpermresidenceStrById($id)
    {
        $regpermresidenceInDb = Regpermresidence::findOne([
            'FID' => $id,
        ]);

        if (!isset($regpermresidenceInDb) || empty($regpermresidenceInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $regpermresidenceInDb->FNAME_L2;
    }
    //endregion

    //region 获得 政治面貌 值
    public static function getPoliticalFaceStrById($id)
    {
        $politicalInDb = HrPolitical::findOne([
            'FID' => $id,
        ]);

        if (!isset($politicalInDb) || empty($politicalInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $politicalInDb->FNAME_L2;
    }
    //endregion

    //region 获得 用户名 值
    public static function getUserStrById($id)
    {
        $userInDb = User::findOne([
            'id' => $id,
        ]);

        if (!isset($userInDb) || empty($userInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $userInDb->username;
    }
    //endregion

    //region 获得 控制单元 值
    public static function getControlUnitStrById($id)
    {
        $controlUnitInDb = CtrlUnit::findOne([
            'FID' => $id,
        ]);

        if (!isset($controlUnitInDb) || empty($controlUnitInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $controlUnitInDb->FNAME_L2;
    }
    //endregion

    //region 获得 父节点 值
    public static function getParentUserGroupStrById($id)
    {
        $parentUserGroupInDb = UserGroup::findOne([
            'FID' => $id,
        ]);

        if (!isset($parentUserGroupInDb) || empty($parentUserGroupInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $parentUserGroupInDb->FNAME_L2;
    }
    //endregion

    //region 获得 用户组 值
    public static function getUserGroupStrById($id)
    {
        $userGroupInDb = UserGroup::findOne([
            'FID' => $id,
        ]);

        if (!isset($userGroupInDb) || empty($userGroupInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $userGroupInDb->FNAME_L2;
    }
    //endregion

    //region 获得 领域 值
    public static function getDomainById($id)
    {
        $recordInDb = Domain::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 职位 org-position 值
    public static function getOrgPositionById($id)
    {
        $recordInDb = OrgPosition::findOne([
            'FID' => $id,
        ]);

        if (!$recordInDb) {
//            return CommonResources::NOT_SET();
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 职位 org-position 值
    public static function getOrgLayerTypeById($id)
    {
        $recordInDb = OrgLayerType::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 行政组 org-admin 值
    public static function getOrgAdminById($id)
    {
        $recordInDb = OrgAdmin::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 行业 industry 值
    public static function getIndustryById($id)
    {
        $recordInDb = Industry::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 业务板块 org-property 值
    public static function getOrgPropertyById($id)
    {
        $recordInDb = OrgProperty::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 离职原因 dimission-reason 值
    public static function getDimissionReasonById($id)
    {
        $recordInDb = DimissionReason::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 入职来源 enroll-source 值
    public static function getEnrollSourceById($id)
    {
        $recordInDb = EnrollSource::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 用工关系类型 值
    public static function getEmployeeModalById($id)
    {
        $employeeModleInDb = EmployeeModle::findOne([
            'FID' => $id,
        ]);

        if (!isset($employeeModleInDb) || empty($employeeModleInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $employeeModleInDb->FNAME_L2;
    }
    //endregion

    //region 获得 员工状态类型 值
    public static function getHrEmployeeFenleiById($id)
    {
        $recordInDb = HrEmployeeFenlei::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 员工 用工关系状态 值
    public static function getHrEmployeeTypeById($id)
    {
        $recordInDb = HrEmployeeType::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 户籍类型 值
    public static function getSSocCensusById($id)
    {
        $recordInDb = HrSSocCensus::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    //region 获得 参保地区 值
    public static function getSSocAreaById($id)
    {
        $recordInDb = HrSSocArea::findOne([
            'FID' => $id,
        ]);

        if (!isset($recordInDb) || empty($recordInDb)) {
//            return Yii::t('app', CommonResources::$NOT_SET);
            return null;
        }
        return $recordInDb->FNAME_L2;
    }
    //endregion

    /**
     * 企业微信部门名称，尽量使用简称，没有简称再用全称
     * @param $org OrgAdmin
     * @return string
     */
    public static function getName4QywxDepartment($org)
    {
        return StringUtil::isNullOrWhiteSpace($org->FSIMPLENAME) ? $org->FNAME_L2 : $org->FSIMPLENAME;
    }

    /**
     * 企业微信部门名称，尽量使用简称，没有简称再用全称,再加上组织编号
     * @param $org OrgAdmin
     * @return string
     */
    public static function getName4OrgTree($org)
    {
        $name = self::getName4QywxDepartment($org);
        return sprintf('%s_%s', $name, $org->FNUMBER);
    }

    /**
     * @param $kdGender integer
     * @return int
     */
    public static function kdGenderToQywxGender($kdGender)
    {
        return $kdGender == Consts::GENDER_MALE ? Consts::GENDER_MALE : Consts::GENDER_FEMALE;
    }

    /**
     * @param $kdDepartmentId string
     * @return string
     */
    public static function kdDepartmentQywxIdToQywxDepartment($kdDepartmentId)
    {
        if (StringUtil::isNullOrWhiteSpace($kdDepartmentId)) {
            $kdDepartmentId = '';
        }
        return sprintf('[%s]', $kdDepartmentId);
    }


    /**
     * @param $fid string
     * @return string
     */
    public static function getPersonPhotoOld($fid)
    {
        $conn = oci_connect('stechr', 'sa', '//122.144.212.225:1521/ORCL');
        $sql = sprintf("select t.FIMAGECONTENTTYPE, t.FIMAGEDATA from T_HR_PERSONPHOTO t WHERE t.FID='%s'", $fid);
        $stmt = oci_parse($conn, $sql);
        oci_execute($stmt);
        $src = '';
        if (ocifetchinto($stmt, $result, OCI_ASSOC + OCI_RETURN_LOBS)) {
            $mime = $result['FIMAGECONTENTTYPE'];
            $contents = $result['FIMAGEDATA'];
            $src = self::data_uri($contents, $mime);
        }
        return $src;
    }

    /**
     * @param $fid string
     * @return string
     */
    public static function getPersonPhotoById($fid)
    {
        $model = HrPersonPhoto::findOne($fid);
        return self::getPersonPhoto($model);
    }

    /**
     * @param $fid string
     * @return string
     */
    public static function getPersonSourcePhotoById($fid)
    {
        $model = HrPersonPhoto::findOne($fid);
        return self::getPersonSourcePhoto($model);
    }

    /**
     * @param $model HrPersonPhoto
     * @return string
     */
    public static function getPersonPhoto($model)
    {
        if (!$model || !is_a($model, HrPersonPhoto::className())) return null;
        $contents = stream_get_contents($model->FIMAGEDATA);
        $src = self::data_uri($contents, $model->FIMAGECONTENTTYPE);
        return $src;
    }

    /**
     * @param $model HrPersonPhoto
     * @return string
     */
    public static function getPersonSourcePhoto($model)
    {
        if (!$model || !is_a($model, HrPersonPhoto::className())) return null;
        $contents = stream_get_contents($model->FIMAGEDATASOURCE);
        $src = self::data_uri($contents, $model->FIMAGECONTENTTYPE);
        return $src;
    }

    /**
     * @param $model EmployeePhoto
     * @return string
     */
    public static function getEmployeePhoto($model)
    {
        if (!$model || !is_a($model, EmployeePhoto::className())) return null;
        $src = self::data_uri($model->image_data, 'image/jpg');
        return $src;
    }

    /**
     * @param $fid string
     * @return array
     */
    public static function getPersonPhotoContent($fid)
    {
        $conn = oci_connect('stechr', 'sa', '//122.144.212.225:1521/ORCL');
        $sql = sprintf("select t.FIMAGECONTENTTYPE, t.FIMAGEDATA from T_HR_PERSONPHOTO t WHERE t.FID='%s'", $fid);
        $stmt = oci_parse($conn, $sql);
        oci_execute($stmt);
        if (ocifetchinto($stmt, $result, OCI_ASSOC + OCI_RETURN_LOBS)) {
            $mime = $result['FIMAGECONTENTTYPE'];
            $contents = $result['FIMAGEDATA'];
        }
        return [
            'mime' => $mime,
            'contents' => $contents
        ];
    }

    /**
     * @param $contents string
     * @param $mime string
     * @return string
     */
    protected static function data_uri($contents, $mime)
    {
        $base64 = base64_encode($contents);
        return ('data:' . $mime . ';base64,' . $base64);
    }


    /**
     * @param $org_admin OrgAdmin
     * @return bool
     */
    public static function checkIsCompany($org_admin)
    {
        $layer = self::getOrgLayerTypeById($org_admin->FLAYERTYPEID);
        if (strcmp($layer, '集团') == 0) {
            return true;
        }
        if (strcmp($layer, '公司') == 0) {
            return true;
        }
        return false;
    }


    /**找到所属组织(即Layer是公司或集团的OrgAdmin)
     * @param $org_admin OrgAdmin
     * @return OrgAdmin
     */
    public static function findSsOrg($org_admin)
    {
        if (!$org_admin) return null;

        if (self::checkIsCompany($org_admin)) {
            return $org_admin;
        }
        if (!StringUtil::isNullOrWhiteSpace($org_admin->FPARENTID)) {
            $parent_org_admin = OrgAdmin::findOne(['FID' => $org_admin->FPARENTID]);
            return self::findSsOrg($parent_org_admin);
        }
        return null;
    }

    /**根据组织编号得到主数据所属组织
     * @param $org_number string
     * @return MdmOrg
     */
    public static function findSsMdmOrgByNumber($org_number)
    {
        $org_admin = OrgAdmin::findOne([
            'FNUMBER' => $org_number
        ]);
        return self::findSsMdmOrgByOrgAdmin($org_admin);
    }

    /**根据OrgAdmin得到主数据所属组织
     * @param $org_admin OrgAdmin
     * @return MdmOrg
     */
    public static function findSsMdmOrgByOrgAdmin($org_admin)
    {
        $ssOrg = self::findSsOrg($org_admin);
        if (!$ssOrg) return null;
//      主数据系统组织的名称是唯一的，如果编号不对，则修改之即可
        $ssMdmOrg = MdmOrg::findOne(['ORGNAME' => $ssOrg->FNAME_L2]);
        if (!$ssMdmOrg) {
            $ssMdmOrg = self::createOrUpdateMdmOrgByOrgAdmin($ssOrg);
            $api = new MdmApiHandler();
            $cResult = $api->syncMdmOrg($ssMdmOrg);
            if (!$cResult->isSuccess) {
                return null;
            }
        }
        $ssMdmOrg = MdmOrg::findOne(['ORGCODE' => $ssOrg->FNUMBER]);
        return $ssMdmOrg;
    }

    /**找到父组织
     * @param $org_admin OrgAdmin
     * @return OrgAdmin
     */
    public static function findParentOrgAdmin($org_admin)
    {
        if (!$org_admin) return null;

        if (!StringUtil::isNullOrWhiteSpace($org_admin->FPARENTID)) {
            $parent_org_admin = OrgAdmin::findOne(['FID' => $org_admin->FPARENTID]);
            return $parent_org_admin;
        }
        return null;
    }

    /**根据OrgAdmin创建一个对应的MdmOrg，但未实例化
     * @param $org_admin OrgAdmin
     * @param $mdm_org MdmOrg
     * @return MdmOrg
     */
    public static function createOrUpdateMdmOrgByOrgAdmin($org_admin, $mdm_org = null)
    {
        if (!$mdm_org) {
            $mdm_org = new MdmOrg();
        }
        $mdm_org->ORGCODE = $org_admin->FNUMBER;
        $mdm_org->ORGNAME = $org_admin->FNAME_L2;
        $parentOrg = self::findParentOrgAdmin($org_admin);
        if ($parentOrg) {
            $parentMdmOrg = MdmOrg::findOne(['ORGCODE' => $parentOrg->FNUMBER]);
            if ($parentMdmOrg) {
                $mdm_org->VVDEF25 = $parentMdmOrg->PK_MDM_ORG;
            }
            $mdm_org->ISNOTUSE = 'Y';
            $mdm_org->DDEF4 = 'Y';
        }
        return $mdm_org;
    }

    /**根据OrgAdmin创建一个对应的MdmDept，但未实例化
     * @param $org_admin OrgAdmin
     * @param $mdm_dept MdmDept
     * @return MdmDept
     */
    public static function createOrUpdateMdmDeptByOrgAdmin($org_admin, $mdm_dept = null)
    {
        if (!$mdm_dept) {
            $mdm_dept = new MdmDept();
        }
        $mdm_dept->DEPARTMENTCODE = $org_admin->FNUMBER;
        $mdm_dept->DEPARTMENTNAME = $org_admin->FNAME_L2;

        $ssMdmOrg = self::findSsMdmOrgByOrgAdmin($org_admin);
        if ($ssMdmOrg) {
            $mdm_dept->SSORG = $ssMdmOrg->PK_MDM_ORG;
        }

        $parentMdmDept = self::findParentMdmDept($mdm_dept);
        if ($parentMdmDept) {
            $mdm_dept->PK_DEF1 = $parentMdmDept->PK_DEPARTMENT;
        }
        DbHelper::set_oracle_nls_timestamp_format(MdmDept::getDb());
        $mdm_dept->STARTDATE = $org_admin->FEFFDT;
        return $mdm_dept;
    }

    /**找到父部门
     * @param $mdm_dept MdmDept
     * @return MdmDept
     */
    public static function findParentMdmDept($mdm_dept)
    {
        if (!$mdm_dept) return null;

        $orgAdmin = OrgAdmin::findOne(['FNUMBER' => $mdm_dept->DEPARTMENTCODE]);
        if (!$orgAdmin) return null;

        if (!StringUtil::isNullOrWhiteSpace($orgAdmin->FPARENTID)) {
            $parent_org_admin = OrgAdmin::findOne(['FID' => $orgAdmin->FPARENTID]);
            if ($parent_org_admin) {
                $parentMdmDept = MdmDept::findOne(['DEPARTMENTCODE' => $parent_org_admin->FNUMBER]);
                return $parentMdmDept;
            }
        }
        return null;
    }

    /**找到父组织
     * @param $mdm_org MdmOrg
     * @return MdmOrg
     */
    public static function findParentMdmOrg($mdm_org)
    {
        if (!$mdm_org) return null;

        $orgAdmin = OrgAdmin::findOne(['FNUMBER' => $mdm_org->ORGCODE]);
        if (!$orgAdmin) return null;

        if (!StringUtil::isNullOrWhiteSpace($orgAdmin->FPARENTID)) {
            $parent_org_admin = OrgAdmin::findOne(['FID' => $orgAdmin->FPARENTID]);
            if ($parent_org_admin) {
                $parentMdmOrg = MdmOrg::findOne(['ORGCODE' => $parent_org_admin->FNUMBER]);
                return $parentMdmOrg;
            }
        }
        return null;
    }

    /**
     * @param $fid string
     * @return QueryInterface
     */
    public static function getPersonBaseQuery($fid)
    {
        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOPP.FADMINORGUNITID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->select([
                'id' => 'TBP.FID',
                'name' => 'TBP.FNAME_L2',
                'number' => 'TBP.FNUMBER',
                'position_name' => 'TOPP.FNAME_L2',
                'position_number' => 'TOPP.FNUMBER',
                'department_name' => 'TOA.FNAME_L2',
                'department_number' => 'TOA.FNUMBER',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
            ]);
        $query->andWhere(['TBP.FID' => $fid]);
        return $query;
    }

    /** 得到一个员工的职位
     * @param $fid string
     * @return string
     */
    public static function getPersonPosition($fid)
    {
        $query = self::getPersonBaseQuery($fid);
        $person = $query->one(Person::getDb());
        if (!$person) return '';
        return $person['position_name'];
    }

    /**找到组织下的员工数
     * @param $org_id string|null
     * @return integer
     */
    public static function getEmployeeCountUnderOrg($org_id)
    {
        $db = Person::getDb();
        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOPP.FADMINORGUNITID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->select([
                'id' => 'TBP.FID',
                'name' => 'TBP.FNAME_L2',
                'number' => 'TBP.FNUMBER',
                'position_name' => 'TOPP.FNAME_L2',
                'position_number' => 'TOPP.FNUMBER',
                'department_name' => 'TOA.FNAME_L2',
                'department_number' => 'TOA.FNUMBER',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
            ]);
        $query->andFilterWhere(['THBET.FISINCOUNT' => 1]);

        if (StringUtil::isNullOrWhiteSpace($org_id) || strtolower($org_id) == 'null' || strtolower($org_id) == 'undefined') {
            return $query->count('*', $db);
        }

        $org = OrgAdmin::findOne([
            'FID' => $org_id
        ]);

        $orgIdParams = [
            'fid' => $org->FID
        ];
        $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
        try {
            $orgIdArr = $cmd->queryColumn();
        } catch (Exception $e) {
            return 0;
        }

        $query->andFilterWhere([
            'in', 'THPP.FPERSONDEP', $orgIdArr
        ]);
        $count = $query->count('*', $db);
        return $count;
    }


    /**
     * @param $org_id string
     * @return array
     */
    public static function getOrgChain($org_id)
    {
        $thisOrg = OrgAdmin::findOne([
            'FID' => $org_id,
        ]);

        $chain = [];
        $parentOrg = $thisOrg;
        while ($parentOrg != null) {
            $chainItem = [
                'id' => urlencode($parentOrg->FID),
                'number' => $parentOrg->FNUMBER,
                'name' => $parentOrg->FNAME_L2,
            ];
            array_push($chain, $chainItem);
            $parentOrg = OrgAdmin::findOne([
                'FID' => $parentOrg->FPARENTID,
            ]);
        }
        $chain = array_reverse($chain);

        return $chain;
    }

    /** 一个组织是否属于另一个组织
     * @param $org4CompareId //待比较的组织id
     * @param $org2CompareId //被测试是否为父节点的id
     * @return bool
     */
    public static function OrgIsBelongToOther($org4CompareId, $org2CompareId)
    {
        if (StringUtil::isNullOrWhiteSpace($org4CompareId) || StringUtil::isNullOrWhiteSpace($org2CompareId)) {
            return false;
        }
        if ($org2CompareId === $org4CompareId)
            return true;

        $org = OrgAdmin::findOne(['FID' => $org4CompareId]);
        if (!$org) return false;

        $parentOrg = OrgAdmin::findOne([
            'FID' => $org->FPARENTID,
        ]);
        if (!$parentOrg) return false;
        $parentOrg4CompareId = $parentOrg->FID;

        return self::OrgIsBelongToOther($parentOrg4CompareId, $org2CompareId);
    }


    /**
     * @param string $accessToken
     * @return bool
     */
    public static function checkAccessTokenIsValid($accessToken = '')
    {
        if (StringUtil::isNullOrWhiteSpace($accessToken)) {
            return false;
        }
        $user = User::findOne([
            'access_token' => $accessToken,
        ]);
        if (!$user) {
            return false;
        }
        return true;
    }

    /**根据工号得到id
     * @param string $number
     * @return string
     */
    public static function getPersonIdByNumber($number = ''){
        $person = Person::findOne(['FNUMBER' => $number]);
        if (!$person){
            return '';
        }
        $id = $person->FID;
        return $id;
    }
}